package com.carnation.servlet;

import java.io.Writer;

import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;

import com.carnation.bean.User;
import com.carnation.service.UserService;
import com.carnation.service.impl.UserServiceImpl;
import com.carnation.utils.Json;
import com.carnation.utils.SessionInfo;
import com.google.gson.Gson;

public class LoginServlet extends HttpServlet{

	private static final long serialVersionUID = 1L;
	private Logger logger = Logger.getLogger(LoginServlet.class);
	
	@Override
	protected void doGet(HttpServletRequest httpServletRequest,HttpServletResponse httpServletResponse){
		doPost(httpServletRequest, httpServletResponse);
	}
	
	@Override
	protected void doPost(HttpServletRequest httpServletRequest,HttpServletResponse httpServletResponse){
		Json json = new Json();
		String msg=null;
		String status = null;
		Gson gson = new Gson();
		String username = httpServletRequest.getParameter("username");
		String password = httpServletRequest.getParameter("password");
		String systype = httpServletRequest.getParameter("systype");
		logger.info("username:" + username);
		logger.info("password:" + password);
		logger.info("systype:" + systype);
		UserService userService = new UserServiceImpl();
		User loginUser = userService.checkLogin(username, password);
		if(loginUser == null){
			msg = "用户名或密码错误";
			status = "400";
		}
		else{
			if(userService.checkPriviledge(loginUser, systype)){
				msg="登录成功";
				status ="200";
				SessionInfo sessionInfo = new SessionInfo();
				sessionInfo.setUser(loginUser);
				httpServletRequest.getSession().setAttribute("sessionInfo", sessionInfo);
				httpServletRequest.getSession().setAttribute("systype", systype);
			}
			else{
				msg = "该用户没有权限进入选择的页面";
				status ="400";
			}
		}
		json.setMsg(msg);
		json.setStatus(status);
		try{
			httpServletResponse.setCharacterEncoding("UTF-8");
			Writer writer = httpServletResponse.getWriter();
			writer.write(gson.toJson(json));
			writer.close();
		}
		catch(Exception e){
			logger.error("登陆发生错误",e);
		}
	}
}
